<script lang="ts" setup name="XtxNumbox">
import { ComponentInternalInstance, getCurrentInstance } from 'vue'
const props = withDefaults(defineProps<{
  modelValue?: number
  max?: number
  min?: number
}>(), {
  modelValue: 1,
  max: 10,
  min: 1
})
// 数据改变传给父组件
const emit = defineEmits<{
  (e: 'update:modelValue', value: number): void
}>()
// 加
const add = () => {
  if (props.modelValue >= props.max) return
  emit('update:modelValue', props.modelValue + 1)
}
// 减
const sub = () => {
  if (props.modelValue <= props.min) return
  emit('update:modelValue', props.modelValue - 1)
}
// input改值
// 强制刷新
const { proxy } = getCurrentInstance() as ComponentInternalInstance
const handleChange = (e: Event) => {
  // change事件什么时候触发 input 中输入内容发生改变 失去焦点
  let val = Number(Number((e.target as HTMLInputElement).value).toFixed())// 建议使用强制类型转换
  if (isNaN(val)) {
    // isNaN() 判断一个数字是否是NaN，not a number 不是数字的数字 不和任何人相等， 自己不等于自己
    val = 1
    // return // val 不符合逻辑变为1
  }
  if (val <= props.min) {
    val = 1
    // return
  }
  if (val >= props.max) {
    val = 20
    // return
  }
  emit('update:modelValue', val)
  proxy!.$forceUpdate()
}
</script>
<template>
  <div class="xtx-numbox">
    <div class="label">数量</div>
    <div class="numbox">
      <a href="javascript:;" @click="sub">-</a>
      <input type="text" :value="modelValue" @change="handleChange" />
      <a href="javascript:;" @click="add">+</a>
    </div>
  </div>
</template>

<style scoped lang="less">
.xtx-numbox {
  display: flex;
  align-items: center;

  .label {
    width: 60px;
    color: #999;
    padding-left: 10px;
  }

  .numbox {
    width: 120px;
    height: 30px;
    border: 1px solid #e4e4e4;
    display: flex;

    >a {
      width: 29px;
      line-height: 28px;
      text-align: center;
      background: #f8f8f8;
      font-size: 16px;
      color: #666;

      &:first-of-type {
        border-right: 1px solid #e4e4e4;
      }

      &:last-of-type {
        border-left: 1px solid #e4e4e4;
      }
    }

    >input {
      width: 60px;
      padding: 0 5px;
      text-align: center;
      color: #666;
    }
  }
}
</style>
